<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
  <th:block th:include="include :: header('Worker')" />
  <th:block th:include="include :: bootstrap-editable-css" />
</head>
<body class="gray-bg">
  <div class="container-div">
    <div class="row">
      <div class="col-sm-12 search-collapse">
        <form id="form-worker">
          <div class="select-list">
            <ul>
              <li>
                <label>Worker：</label>
                <input type="text" name="worker" th:value="${worker}" placeholder="移除后可输入`host:port`来查询" autocomplete="off" />
              </li>
              <li>
                <a class="btn btn-primary btn-rounded btn-sm" onclick="searchWorker()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                <a class="btn btn-warning btn-rounded btn-sm" onclick="resetForm()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
              </li>
            </ul>
          </div>
        </form>
      </div>

      <div class="btn-group-sm" id="toolbar" role="group">
        <a th:if="${not #lists.isEmpty(workers)}" class="btn btn-success" onclick="modifyAllWorkerMaximumPoolSize()">
          <i class="fa fa-edit"></i> 修改全部
        </a>
        <a class="btn btn-success" onclick="addWorker()">
          <i class="fa fa-plus"></i> 添加Worker
        </a>
      </div>

      <div class="col-sm-12 select-table table-striped">
        <table id="bootstrap-table"></table>
      </div>
    </div>
  </div>

  <div th:include="include :: footer"></div>
  <th:block th:include="include :: bootstrap-table-fixed-columns-js" />
  <th:block th:include="include :: bootstrap-table-editable-js" />

  <script th:inline="javascript">
    const prefix = ctx + "disjob/mygroup";

    $(function () {
      const options = {
        data: [[${workers}]],
        sidePagination: "client",
        showSearch: false,
        showRefresh: false,
        showToggle: true,
        showColumns: true,
        fixedColumns: true,
        fixedNumber: 3,
        onEditableSave: modifyOneWorkerMaximumPoolSize,
        columns: [{
          field: 'workerId',
          title: 'Worker Id'
        },
        {
          field: 'host',
          title: 'Host'
        },
        {
          field: 'port',
          title: 'Port'
        },
        {
          field: 'pingTime',
          title: 'Ping time(ms)'
        },
        {
          field: 'maximumPoolSize',
          title: '最大线程数',
          editable: {
            type: 'text',
            validate: validateMaximumPoolSize
          }
        },
        {
          field: 'currentPoolSize',
          title: '当前总线程数'
        },
        {
          field: 'activePoolSize',
          title: '活跃线程数'
        },
        {
          field: 'idlePoolSize',
          title: '空闲线程数'
        },
        {
          field: 'queueTaskCount',
          title: '队列等待任务数'
        },
        {
          field: 'completedTaskCount',
          title: '已完成任务数'
        },
        {
          field: 'jvmThreadActiveCount',
          title: 'JVM活跃线程数'
        },
        {
          field: 'closed',
          title: '线程池是否已关闭',
          formatter: function(value, row, index) {
            return value ? '<span class="badge badge-success">是</span>' : '<span class="badge badge-info">否</span>';
          }
        },
        {
          field: 'alsoSupervisor',
          title: '是否同为Supervisor',
          formatter: function(value, row, index) {
            return value ? '<span class="badge badge-success">是</span>' : '<span class="badge badge-info">否</span>';
          }
        },
        {
          field: 'version',
          title: 'Version',
          cellStyle: function (value, row, index) {
            return { css: { "white-space": "nowrap" } }
          }
        },
        {
          field: 'startupTime',
          title: '启动时间',
          cellStyle: function (value, row, index) {
            return { css: { "white-space": "nowrap" } }
          }
        },
        {
          title: '操作',
          align: 'center',
          formatter: function (value, row, index) {
            const actions = [];
            actions.push("<a class='btn btn-danger btn-rounded btn-xs' href='javascript:void(0)' onclick='operate(&quot;REMOVE_WORKER&quot;, &quot;移除该Worker&quot;, &quot;" + row.workerId + "&quot;, &quot;" + row.host + "&quot;, " + row.port + ")'><i class='fa fa-remove'></i> 移除Worker</a> ");
            return '<a tabindex="0" class="btn btn-info btn-rounded btn-xs" role="button" data-container="body" data-placement="left" data-toggle="popover" data-html="true" data-trigger="hover" data-content="' + actions.join('') + '"><i class="fa fa-chevron-circle-right"></i> 操作</a>';
          }
        }]
      };

      $.table.init(options);
    });

    function modifyOneWorkerMaximumPoolSize(field, row, rowIndex, oldValue) {
      if (field !== "maximumPoolSize") {
        row[field] = oldValue;
        $.modal.msgError("只能更新['maximumPoolSize']字段");
        return;
      }
      const newValue = parseInt($.trim(row[field]));
      if (oldValue === newValue) {
        // reset to oldValue(none left or right blank)
        row[field] = oldValue;
        return;
      }
      const params = {
        "group": [[${group}]],
        "workerId": row.workerId,
        "host": row.host,
        "port": row['port'],
        "action": "MODIFY_MAXIMUM_POOL_SIZE",
        "data": newValue
      };
      $.operate.post(prefix + "/configure_one_worker", params, function (result) {
        row[field] = (result.code === 0) ? newValue : oldValue;
      }, false);
    }

    function modifyAllWorkerMaximumPoolSize() {
      layer.open({
        type: 1,
        title: '修改全部Worker的最大线程数',
        btn: ['确定', '取消'],
        content: '<input type="text" class="layui-layer-input" placeholder="请输入要修改的最大线程数目标值">',
        skin: 'layui-layer-prompt',
        resize: false,
        success: function (layero, index) {
          layero.find('.layui-layer-input').focus();
        },
        yes: function (index, layero) {
          const input = layero.find('.layui-layer-input');
          const value = input.val().trim();
          const msg = validateMaximumPoolSize(value);
          if (msg) {
            layer.tips(msg, input, {tips: 1});
            return;
          }
          const params = {
            "group": [[${group}]],
            "action": "MODIFY_MAXIMUM_POOL_SIZE",
            "data": value
          };
          $.operate.post(prefix + "/configure_all_worker", params, function (result) {
            if (result.code === 0) {
              /*
              const src = prefix + "/worker?group=" + [[${group}]];
              const iframe = $(window.parent.document).find("iframe[src='" + src + "']");
              iframe.attr("src", src);
              */
              location.reload();
              layer.close(index);
            }
          }, false);
        }
      });
    }

    function validateMaximumPoolSize(value) {
      if (!value || !value.trim()) {
        return '不能为空';
      }
      if (!/^[1-9]\d*$/g.test(value.trim())) {
        return '请输入正整数';
      }
      if (parseInt(value) > 32767) {
        return '不能大于 32767';
      }
    }

    function addWorker() {
      layer.open({
        type: 1,
        title: '添加Worker',
        btn: ['确定', '取消'],
        content: '<input type="text" class="layui-layer-input" placeholder="请输入待添加Worker的`host:port`">',
        skin: 'layui-layer-prompt',
        resize: false,
        success: function (layero, index) {
          layero.find('.layui-layer-input').focus();
        },
        yes: function (index, layero) {
          const input = layero.find('.layui-layer-input');
          const value = input.val().trim();
          if (!/^[A-Za-z0-9.]+:\d+$/g.test(value)) {
            layer.tips("无效的`host:port`", input, {tips: 1});
            return;
          }
          const params = {
            "group": [[${group}]],
            "workerId": null,
            "host": value.split(":")[0],
            "port": value.split(":")[1],
            "action": "ADD_WORKER"
          };
          $.operate.post(prefix + "/configure_one_worker", params, function (result) {
            if (result.code === 0) {
              //location.reload();
              resetForm();
              layer.close(index);
            }
          }, false);
        }
      });
    }

    function operate(action, msg, workerId, host, port) {
      const params = {
        "group": [[${group}]],
        "workerId": workerId,
        "host": host,
        "port": port,
        "action": action
      };
      $.modal.confirm("确认要 `" + msg + "` 吗？", function () {
        $.operate.post(prefix + "/configure_one_worker", params, function (result) {
          if (result.code === 0) {
            resetForm();
          }
        }, false);
      });
    }

    function searchWorker() {
      const href = window.location.href;
      window.location.href = href.split("\?")[0] + "?group=" + [[${group}]] + "&worker=" + $("input[name='worker']").val()
    }

    function resetForm() {
      $("input[name='worker']").val("");
      searchWorker();
    }
  </script>

</body>
</html>
